#!/usr/bin/perl

# load module
use strict;
use warnings;

unless (eval{require Device::SerialPort}) {
	print "Not Found Device::SerialPort";
	exit (1);
}


# set argument
my $arg_device = $ARGV[0];
my $arg_patternfile = $ARGV[1];
my $arg_lockfile = $ARGV[2];


# check argument length
if (@ARGV < 3) {
	print "Not enough argument!\n[pattern file] [lock file]\n";
	exit (1);
} elsif (@ARGV > 3) {
	print "To match argument!\n[pattern file] [lock file]\n";
	exit (1);
}


# check lock file exist
unless (-e $arg_lockfile) {
	exit (1);
}


# open serialport
unless (-e $arg_device) {
	exit (1);
}
my $port = Device::SerialPort -> new($arg_device);

$port -> databits(8);
$port -> baudrate(57600);
$port -> parity("none");
$port -> stopbits(1);
$port -> lookclear();


# bootup delay
select(undef, undef, undef, 6);


# read pattern file
open (FH, "<$arg_patternfile");
my @file = <FH>;
close (FH);


# send pattern to serialport
while (-e $arg_lockfile) {
	foreach my $fileline (@file) {
		my @line = split(/=/, $fileline);
		my @pattern = split(/,/, $line[1]);
		
		foreach my $value (@pattern) {
			$value =~ s/\r//;
			$value =~ s/\n//;
			
			$port -> write($value);
			select(undef, undef, undef, 0.004);
			#select(undef, undef, undef, 0.003);
		}
		
		# display clear
		select(undef, undef, undef, 3);
		$port -> write("R");
		select(undef, undef, undef, 0.004);
		#select(undef, undef, undef, 0.003);
	}
}

# close serialport
$port -> close;

